#include "stdafx.h"
#include "service\storage\file\DivisionFileService.h"
#include "service\storage\file\BaseFileService.h"
#include "service\storage\file\TeamFileService.h"
#include "service\storage\file\MatchFileService.h"
#include "model\Division.h"
#include "lib\ErrorHandler.h"

// Constructors and deconstructor
DivisionFileService::DivisionFileService() {
}


DivisionFileService::DivisionFileService(const std::string fname) : BaseFileService(fname) {
}


DivisionFileService::DivisionFileService(std::fstream& file) : BaseFileService(file) {
}


DivisionFileService::~DivisionFileService() {
}


BaseFileService& DivisionFileService::Load(BaseModel* model) {
  Division *division = reinterpret_cast<Division*>(model);
  if (division->name().empty()) {
    file() >> *division;
  }
  if (division->Validate()) {
    int numteams;
    file() >> numteams;
    file().ignore();
    TeamFileService tfs(file());
    for (int i = 0; i < numteams; ++i) {
      Team team;
      tfs.Load(&team);
      if (team.Validate())
        division->AddTeam(team);
    }
  } else {
    ErrorHandler::DisplayError("An unexpected error has occured while reading from file.");
    ErrorHandler::DisplayModelErrors(*division);
  }
  return *this; 
}

BaseFileService& DivisionFileService::Save(const BaseModel& model) {
  const Division& division = reinterpret_cast<const Division&>(model);
  std::cout << division.name();
  file() << division << '\n';
  file() << division.NumTeams() << '\n';
  TCollection<Team>::CollectionPair teamiters = division.GetTeams();
  TeamFileService tfs(file());
  for (; teamiters.first != teamiters.second; ++teamiters.first) {
    tfs.Save(*teamiters.first);
  }
  return *this;
}

BaseFileService& DivisionFileService::SaveSchedule(const Division& division) {


  return *this;
}